import { defineStore } from "pinia";
import { notification } from "ant-design-vue";

// 系统全局的变量 单向往后传递，不发生改变
const appStore = defineStore("appStore", {
  state: () => {
    return {
      aryFieldType: new Array(), //字段类型列表
      aryVgt: [],
      arySrmType: [],
      aryVisitLimitType: [],
      aryComputAction: [],
      aryFieldValueEvaluation: [],
      aryRecordValueRuleDetail: [],
      allMyModels: [],
      allModelFieldMap: new Map(), // 模型字段关联前端缓存
      pubKey: undefined,
      otherUsers: [], // 其他用户的信息
    };
  },
});

// 不同的视图间传递的变量
const channel = defineStore("channel", {
  state: () => {
    return {
      selectedModel: undefined,
      selectedOrder: undefined, // 当前查询加载记录的顺序
      visitToken: undefined, // 当前正在适应的访问请求
      recordInEditting: undefined, // 当前正在编辑的模型记录,undefined则表示是新建
      uploadData: undefined, // 上传成功的文件信息
    };
  },
});

const armErrorHandler = (arm) => {
  notification.error({
    message: "",
    description: arm.error,
  });
};

const axiosErrorHandler = (e) => {
  // console.error(e);
  if (e.response && e.response.status) {
    switch (e.response.status) {
      case 403:
      case 401:
        window.parent.location.reload();
        break;
      case 500:
        notification.error({
          message: "",
          description: e.response.data.error.cause.replaceAll('"', ""),
        });
        break;
    }
  }
};

const alert = (msg) => {
  notification.info({
    message: "",
    description: msg,
  });
};

const isStringValue = (str) => {
  return str != undefined && str != null && str.trim().length > 0;
};

const clearProperty = (obj) => {
  for (const attr in obj) {
    delete obj[attr];
  }
};

const clearArray = (ary) => {
  ary.splice(0, ary.length);
};

const useful = (obj) => {
  return obj != undefined && obj != null;
};

const usefulArray = (ary) => {
  return ary != undefined && ary != null && ary.length > 0;
};

const _appStore = appStore();

const apiGetArm = (url, fn, showArmError = true) => {
  fetch(url, {
    headers: {
      Authorization: `Bearer ${localStorage.getItem("token")}`,
    },
  })
    .then((r) => {
      // console.log(r);
      if (r.headers.token && r.headers.token.length > 0) {
        // console.log("refresh token to " + response.headers.token);
        localStorage.setItem("token", r.headers.token);
      }
      return r.json();
    })
    .then((arm) => {
      // console.log(arm);
      if (arm.ok) {
        fn(arm.data);
      } else if (showArmError) {
        armErrorHandler(arm);
      }
    })
    .catch((e) => {
      axiosErrorHandler(e);
    });
};

const apiPostArm = (url, pd, fn, showArmError = true) => {
  if (pd == undefined || pd == null) {
    fetch(url, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
    })
      .then((r) => {
        // console.log(r);
        if (r.headers.token && r.headers.token.length > 0) {
          // console.log("refresh token to " + response.headers.token);
          localStorage.setItem("token", r.headers.token);
        }
        return r.json();
      })
      .then((arm) => {
        // console.log(arm);
        if (arm.ok) {
          fn(arm.data);
        } else if (showArmError) {
          armErrorHandler(arm);
        }
      })
      .catch((e) => {
        axiosErrorHandler(e);
      });
  } else {
    fetch(url, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(pd),
    })
      .then((r) => {
        // console.log(r);
        if (r.headers.token && r.headers.token.length > 0) {
          // console.log("refresh token to " + response.headers.token);
          localStorage.setItem("token", r.headers.token);
        }
        return r.json();
      })
      .then((arm) => {
        // console.log(arm);
        if (arm.ok) {
          fn(arm.data);
        } else if (showArmError) {
          armErrorHandler(arm);
        }
      })
      .catch((e) => {
        axiosErrorHandler(e);
      });
  }
};

const runWithFieldCache = (modelId, fn) => {
  let fields = _appStore.allModelFieldMap.get(modelId);
  if (usefulArray(fields)) {
    fn(fields);
  } else {
    apiGetArm("/api/v1/model/list-field/" + modelId, (d) => {
      _appStore.allModelFieldMap.set(modelId, d);
      fn(d);
    });
  }
};

export default {
  axiosErrorHandler,
  armErrorHandler,
  alert,
  isStringValue,
  clearProperty,
  clearArray,
  useful,
  usefulArray,
  runWithFieldCache,
  apiGetArm,
  apiPostArm,
  appStore,
  channel,
};
